package feng.demo.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.util.SaResult;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
//拦截satoken产生的异常，以自己的方式返回
public class SatokenExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 设置响应内容类型
        response.setContentType("application/json;charset=utf-8");
        String errorMessage=null;
        int value = HttpStatus.UNAUTHORIZED.value();
        if (ex instanceof NotLoginException) {
            NotLoginException e = (NotLoginException) ex;
            if ("-1".equals(e.getType())) {
                errorMessage = "未登录，请先登录";
            } else if ("-2".equals(e.getType())) {
                errorMessage = "登录失效，请重新登录";
            } else if ("-3".equals(e.getType())) {
                errorMessage = "登录失效，请重新登录";
            } else if ("-4".equals(e.getType())) {
                errorMessage = "账号已被顶下线，请重新登录";
            } else if ("-5".equals(e.getType())) {
                errorMessage = "账号已被踢下线，请重新登录";
            } else {
                errorMessage = "未登录，请登录";
            }
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
        if (ex instanceof NotRoleException) {
            NotRoleException x = (NotRoleException) ex;
            // 设置响应状态码
            response.setStatus(HttpStatus.FORBIDDEN.value());
            value=HttpStatus.FORBIDDEN.value();
            if(x.getRole()!=null){
                errorMessage="权限不足";
            }else errorMessage = "登录失效，请重新登录";
        }

        try (PrintWriter writer = response.getWriter()) {
            writer.write(SaResult.get(value,errorMessage,"").toString());
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return new ModelAndView();
    }
}
